/**
 * @description 封装数据库相关操作
 * @version 1.0.0
 * @author 钟宇飞
 */
const mysql = require('mysql');
class DBUitls {
  /**
   * @description 获取一个数据库连接
   * @returns {mysql.Connection} 返回数据库连接
   */
  getConn() {
    let conn = mysql.createConnection({
      host: '127.0.0.1',
      port: 3306,
      user: 'root',
      password: '123',
      database: 'rental_house',
      multipleStatements: true
    });
    return conn;
  }

  /**
   * @description 执行一条SQL语句
   * @param {string} strSql  要执行的SQL语句
   * @param {[]} ps 执行SQL语句的参数
   * @returns {Promise<[]|mysql.OkPacket>} 数据库执行的结果
   */
  executeSql(strSql, ps = []) {
    return new Promise((resolve, reject) => {
      let conn = this.getConn();
      conn.connect();
      conn.query(strSql, ps, (error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
        conn.end();
      });
    });
  }
}

module.exports = DBUitls;
